#include "project_config.h"
#include "qelib.h"
#include "tlsf.h"
#include "xuartlite_l.h"

QELOG_DOMAIN("main");

#if (LOG_ENABLE == 1)
static void log_init(void)
{
    qe_u32 flags;
    flags = QELOG_DM | QELOG_LV | QELOG_RECUR | QELOG_CL;
    qelog_init(LOG_LEVEL, flags);

#if (LOG_BUF_ENABLE == 1)
    char *buffer;
    buffer = QE_malloc(LOG_BUF_SIZE);
    QElog_set_buffer(buffer, LOG_BUF_SIZE);
#endif
}
#endif

void vApplicationAssertMsg(const char *pcFile, uint32_t ulLine, const char *msg)
{
    qe_fatal("AssertMsg: %s:%d %s", pcFile, ulLine, msg);
    while (1);
}

void app_assert(const char *ex, const char *file, qe_size line)
{
    qe_fatal("Assert: %s %s:%d", ex, file, line);
    while (1);
}

typedef void* (*qemem_malloc_fn)(qe_size size);

//static tlsf_t tlsf;
//static void *tlsf_adapte_malloc(qe_size size)
//{
//    return tlsf_malloc(tlsf, size);
//}
//
//static void *tlsf_adapte_realloc(void *ptr, qe_size size)
//{
//    return tlsf_realloc(tlsf, ptr, size);
//}
//
//static void tlsf_adapte_free(void *ptr)
//{
//    tlsf_free(tlsf, ptr);
//}
//
//static qemem_allocator tlsf_allocator = {
//	.malloc  = (qemem_malloc_fn)tlsf_adapte_malloc,
//    .free    = tlsf_adapte_free,
//    .calloc  = QE_NULL,
//    .realloc = tlsf_adapte_realloc,
//};

static char tlsf_heap[HEAP_SIZE];

static void mem_init(void)
{
    //tlsf = tlsf_create_with_pool(tlsf_heap, sizeof(tlsf_heap));
	//qemem_set_allocator(&tlsf_allocator);
	qemem_set_pool(tlsf_heap, sizeof(tlsf_heap));
}

int main(void)
{
    /* Memory Initialization */
    mem_init();

#if (LOG_ENABLE == 1)
    /* Log Initialization */
    log_init();
#endif

    /* Assert Hook Setting */
    qe_assert_set_hook(app_assert);

    /* Initcall */
    qe_initcall();

    return 0;
}
